'use strict';
const db = uniCloud.database();
const UniID = require('uni-id-common');

exports.main = async (event, context) => {
	let body = event;
	if (event.body !== undefined) {
		body = JSON.parse(event.body);
	}
	const uniIDIns = UniID.createInstance({ context })
	const { uniIdToken, number } = body;

	if (!uniIdToken || number === undefined) {
		return { code: 400, msg: "uniIdToken 和次数不能为空" };
	}
	if( number < 0){
		return { code: 401, msg: "次数不能小于0" };
	}
	try {
		// 通过 token 获取用户信息
		const verifyRes = await uniIDIns.checkToken(uniIdToken);
		if (verifyRes.code !== 0) {
			return { code: 401, msg: "无效的 Token，请重新登录" };
		}

		const uid = verifyRes.uid;

		// 获取用户集合
		const userCollection = db.collection('uni-id-users');

		// 更新字段 required_number
		const updateData = { required_number: number };
		await userCollection.doc(uid).update(updateData);

		return { code: 200, msg: "更新成功", data: updateData };
	} catch (error) {
		return { code: 500, msg: "数据库更新失败", error };
	}
};
